<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="container"></div>

    <script>
      function observer(target) {
        const div = document.querySelector("#container");
        const ob = {};
        const props = Object.keys(target);
        for (const prop of props) {
          Object.defineProperty(ob, prop, {
            get() {
              return target[prop];
            },
            set(val) {
              target[prop] = val;
              render();
            },
            enumerable: true, // 需要手动设置enumerable属性，因为get，set默认是不允许遍历的
          });
        }

        render();
        function render() {
          let html = "";
          for (const prop of Object.keys(ob)) {
            html += `<p><span>${prop}</span><span>${ob[prop]}</span></p>`;
          }
          div.innerHTML = html;
        }

        return ob;
      }

      const target = {
        a: 1,
        b: 2,
      };

      const obj = observer(target);
    </script>
  </body>
</html>
